package com.kungfuhacking.wristbandpro.base;

import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.support.multidex.MultiDex;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.kungfuhacking.wristbandpro.R;
import com.kungfuhacking.wristbandpro.chat.bean.EmoBean;
import com.kungfuhacking.wristbandpro.mqtt.MQTTService;
import com.kungfuhacking.wristbandpro.mqtt.MqttManager;
import com.kungfuhacking.wristbandpro.utils.ParserBrowXml;
import com.squareup.leakcanary.LeakCanary;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.ShareSDK;
import mqttresource.MqttException;

/**
 * application
 * Created by Aaron on 17/3/28.
 */

public class Mapplication extends Application {

    private String TAG = getClass().getSimpleName();
    private Intent serviceIntent;
    private HashMap<String, String> emos;
    private List<EmoBean> emoBeanList;

    @Override
    public void onCreate() {
        super.onCreate();

        //fresco图片加载初始化
        Fresco.initialize(this);
//        LogUtil.d(TAG, "sha1值:" + sHA1(getApplicationContext()));

        LeakCanary.install(this);//检测内存泄露

        //zxing扫描
        ZXingLibrary.initDisplayOpinion(this);

        //极光推送
//        JPushInterface.setDebugMode(true);//是否开启debug模式
        JPushInterface.init(this);
        setPushNotificationBuilder();
        clearNotification();
        //sharesdk分享
        ShareSDK.initSDK(this);

        // 在Appliction里面设置我们的异常处理器为UncaughtExceptionHandler处理器
//        CrashHandler handler = CrashHandler.getInstance();
//        handler.init(getApplicationContext());

    }

    private void setPushNotificationBuilder() {

        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(this);
        builder.statusBarDrawable = R.mipmap.jpush_notification_icon;
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL;
//                | Notification.FLAG_SHOW_LIGHTS;  //设置为自动消失和呼吸灯闪烁
        builder.notificationDefaults = Notification.DEFAULT_SOUND
                | Notification.DEFAULT_VIBRATE;
//                | Notification.DEFAULT_LIGHTS;  // 设置为铃声、震动、呼吸灯闪烁都要
        JPushInterface.setPushNotificationBuilder(1, builder);

    }

    private void clearNotification() {
        //清除通知栏上的所有通知
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
    }

//    public String sHA1(Context context) {
//        try {
//            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
//            byte[] cert = info.signatures[0].toByteArray();
//            MessageDigest md = MessageDigest.getInstance("SHA1");
//            byte[] publicKey = md.digest(cert);
//            StringBuffer hexString = new StringBuffer();
//            for (int i = 0; i < publicKey.length; i++) {
//                String appendString = Integer.toHexString(0xFF & publicKey[i])
//                        .toUpperCase(Locale.US);
//                if (appendString.length() == 1)
//                    hexString.append("0");
//                hexString.append(appendString);
//            }
//            return hexString.toString();
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * 获取表情的map集合 key是表情的匹配符如[满意], value是图片的名称
     *
     * @return
     */
    public Map<String, String> getEmoMap() {

        if (emos == null || emos.size() == 0) {

            try {
                emos = ParserBrowXml.getInfo(getResources().getAssets().open("brow.xml"));
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        return emos;

    }

    /**
     * 获取表情的list集合
     *
     * @return
     */
    public List<EmoBean> getEmoList() {

        if (emoBeanList == null || emoBeanList.size() == 0) {
            try {
                emoBeanList = ParserBrowXml.getListInfo(getResources().getAssets().open("brow.xml"));
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        return emoBeanList;
    }

    //启动服务, 登录mqtt
    public void loginMqtt() {
        serviceIntent = new Intent(this, MQTTService.class);
        startService(serviceIntent);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    /**
     * 退出mqtt
     */
    public void exitMqtt() throws MqttException {
        stopService();
    }


    public void exit() {

        try {
            stopService();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }

    }

    public void stopService() throws MqttException {
        if (MqttManager.getInstance().getMqttClient() != null && MqttManager.getInstance().getMqttClient().isConnected())
            MqttManager.getInstance().getMqttClient().disconnect();

        //关闭聊天服务
        if (serviceIntent != null)
            stopService(serviceIntent);
    }
}
